
package es.upm.dit.gsi.opactv.searchengines;

import es.upm.dit.gsi.opactv.util.Connection;
import es.upm.dit.gsi.opactv.util.FormatData;
import es.upm.dit.gsi.opactv.Book;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class Librofilia implements SearchEngine {

    private Connection conn = new Connection();
    private FormatData fd = new FormatData();
    private Book book;

    public Librofilia() {
        // COLLECTION!
    }

    public void set(String title, String author, String tags) {
        // NADA
    }

    public ArrayList<Book> getBooks() {
        return new ArrayList();
    }

    public void completeBook(Book book) {
        this.book = book;
        String thisTitle = cleanAccents(book.getTitle());
        String thisAuthor = cleanAccents(book.getAuthor());
        getBook(thisTitle, thisAuthor);
        String description = book.getDescription();
        if (description==null || description.equals("")) {
            book.addDescription(getDescription());
        }
        for (String tag : getTags()) book.addTag(tag);
        String cover = book.getCover();
        if (cover==null || cover.equals("")) book.addCover(getCover());
    }

    public String getDescription() {
        String data = conn.get(book.getOptional("LIBROFILIA:URL"));
        String container = fd.format(data, "Sinopsis", "clear alto10");
        String description = fd.format(container, "\"></div>", "<div");
        return fixDescription(description);
    }

    public ArrayList<String> getTags() {
        ArrayList<String> tags = new ArrayList();
        String data = conn.get(book.getOptional("LIBROFILIA:URL"));
        String container = fd.format(data, "txt_gris1", "</p>");
        int index;
        while ((index=container.indexOf("<a"))!=-1) {
            container = container.substring(index+1);
            tags.add(fd.format(container, ">", "<"));
        }
        return tags;
    }

    public String getCover() {
        String data = conn.get(book.getOptional("LIBROFILIA:URL"));
        String coverID = fd.format(data, "imagescaratulas/", "\"");
        if (!coverID.equals("")) {
            return "http://www.librofilia.com/imagescaratulas/" + coverID;
        } else return "";
    }

    private void getBook(String title, String author) {
        String url = "http://www.librofilia.com/busca/" +
                     cleanAccents(urlEncoder(title));
        String data = conn.get(url);
        if (data.indexOf("0 coincidencias")==-1) {
            int index;
            String listContainer = fd.format(data, "grid_9", "clear alto20");
            while ((index=listContainer.indexOf("txt_mediano"))!=-1) {
                String bookAuthor, bookOptional;
                listContainer = listContainer.substring(index+1);
                String container = fd.format(listContainer, "txt_azul1\">", "</p>");
                bookOptional = fd.format(container, "href=\"", "\"");
                container = fd.format(listContainer, "\"txt_azul1\">", "</p>");
                bookAuthor = fd.format(container, ">", "<");
                if (checkAuthor(bookAuthor)) {
                    book.addOptional("LIBROFILIA:URL", bookOptional);
                    break;
                }
            }
        }
    }

    private boolean checkAuthor(String author) {
        StringTokenizer st = new StringTokenizer(author, ",");
        if (!st.hasMoreTokens() || st.countTokens()!=2) return false;
        else {
            String surname = st.nextToken().trim();
            author = st.nextToken().trim() + " " + surname;
            if (author.indexOf(book.getAuthor())!=-1) return true;
            else return false;
        }
    }
    
    private String fixDescription(String description) {
        String[][] fix = {{"&quot;","\""},{"<br />"," "}};
        for (int i=0; i<fix.length; i++) {
            if (description.indexOf(fix[i][0])!=-1) {
                description = description.replace(fix[i][0], fix[i][1]);
            }
        }
        return description;
    }

    private String cleanAccents(String data) {
        data = data.replaceAll("á", "a");
        data = data.replaceAll("é", "e");
        data = data.replaceAll("í", "i");
        data = data.replaceAll("ó", "o");
        data = data.replaceAll("ú", "u");
        return data;
    }

    private String urlEncoder(String params) {
        String encoded = "";
        try {
            encoded = URLEncoder.encode(params, "UTF-8");
        } catch (Exception ex) {
            // System.err.println(ex);
        } finally {
            return encoded;
        }
    }

}
